package com.topone.service.impl;

import com.topone.Const.Model;
import com.topone.Enum.ResultEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Exception.FanZoneServiceException;
import com.topone.Utils.CodeUntil;
import com.topone.Utils.DaoUtils;
import com.topone.dataObject.Bussiness;
import com.topone.dataObject.Mapper.UserCouponMapper;
import com.topone.dataObject.TcUser;
import com.topone.dataObject.TcUserCoupon;
import com.topone.dto.BussinessDTO;
import com.topone.dto.TcCouponDTO;
import com.topone.dto.TcUserCouponDTO;
import com.topone.repository.BussinessRepository;
import com.topone.repository.TcUserCouponRepository;
import com.topone.service.TcCouponService;
import com.topone.service.TcUserCouponService;
import com.topone.service.TcUserService;
import com.topone.sms.SmsService;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by Administrator on 2017/11/6,0006.
 */
@Service
@Slf4j
public class TcUserCouponServiceImpl implements TcUserCouponService {
    @Autowired
    private TcUserCouponRepository repository;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private SmsService smsSohuService;

    @Autowired
    private TcUserService tcUserService;

    @Autowired
    private CodeUntil codeUntil;

    @Autowired
    private BussinessRepository bussinessRepository;

    @Autowired
    private TcCouponService tcCouponService;

    public List<TcUserCoupon> findUserConpon(String userId, String status) {
        List<TcUserCoupon> userCouponList = new ArrayList<>();
        userCouponList = repository.findByStatusEquals(status);
        return userCouponList;
    }

    //根据用openid查询优惠券信息
    @Override
    public List<BussinessDTO> findCouponByopenid(TcUserCoupon tcUserCoupon) {
        List<BussinessDTO> bussinessDTOList = new ArrayList<>();
        try {
            bussinessDTOList = userCouponMapper.findCouponByopenid(tcUserCoupon);

        } catch (Exception e) {
            log.error("【查询个人优惠券】失败,{}", tcUserCoupon);
            e.printStackTrace();
            throw new FanZoneException(ResultEnum.FIND_USERCOUPON_ERROR);

        }
        return bussinessDTOList;
    }

    //查询所有未支付的优惠券订单
    @Override
    public List<TcUserCouponDTO> findAllUserCoupon(Integer status) {
        return userCouponMapper.findUserCoupon(status);
    }

    //更新用户超时未支付订单回退
    @Override
    @Transactional
    public void cancelUserCoupon(String id) {
        userCouponMapper.cancelUserCoupon(id);
    }

    //商家核销券, 查询券

    @Override
    public List<TcUserCouponDTO> findUserCouponList(String userPhone, String userCouponCode) {
        List<TcUserCouponDTO> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(userPhone)) {
            list = userCouponMapper.findUserCouponListByPhone(userPhone);
        } else if (StringUtils.isNotEmpty(userCouponCode)) {
            list = userCouponMapper.findUserCouponListByCode(userCouponCode);
        }
        return list;
    }

    @Override
    @Transactional
    @Synchronized
    public String updateUserCouponById(String userCouponId) {
        TcUserCouponDTO tcUserCoupon = userCouponMapper.countUserCoupon(userCouponId);
        if (Objects.nonNull(tcUserCoupon)) {
            try {
                Bussiness bussiness = bussinessRepository.getOne(tcUserCoupon.getTcCouponDTO().getBussinessDTO().getBussinessId());
                TcUser tcUser = tcUserService.findByopenid(tcUserCoupon.getBuyerOpenid());
                String result = codeUntil.updateCouponStatus(tcUserCoupon.getCouponCode(), Model.COUPONCODE_USED);
                if (StringUtils.isEmpty(result)) {
                    log.info("用户优惠券code不存在:{}", tcUserCoupon);
                    return "error";
                }
                if (Objects.nonNull(tcUser) && StringUtils.isNotEmpty(tcUser.getHandPhone())
                        && Objects.nonNull(bussiness)) {
                    userCouponMapper.updateuserCoupon(userCouponId);
                    boolean backdoor = tcUser.getHandPhone().startsWith("99");
                    smsSohuService.sendCheckCouponSmsCode
                            (tcUser.getHandPhone(), tcUser.getUserName(), tcUserCoupon.getTcCouponDTO().getCouponName(),
                                    bussiness.getBussinessName(), backdoor);
                    log.info("发送短信成功");
                    return "success";
                } else {
                    throw new FanZoneServiceException("用户手机号码为空 无法发送短信");
                }
            } catch (Exception e) {
                log.info("{}", e.fillInStackTrace());
                return "error";
            }
        } else {
            return "error";
        }
    }

    //查询所有用户超时未使用优惠券
    @Override
    @Transactional
    @Scheduled(cron = "0 0 0 * * ?")
    public void findUserCouponOvertime() {
        List<TcUserCouponDTO> list = userCouponMapper.findUserCouponOverTime();
        try {
            for (int i = 0; i < list.size(); i++) {
                cancelUserCouponUnuse(list.get(i).getId());
                String result = codeUntil.updateCouponStatus(list.get(i).getCouponCode(), Model.COUPONCODE_USED);
                if (StringUtils.isEmpty(result) || result == null) {
                    log.info("用户优惠券code不存在:{}" + list.get(i).getCouponCode());
                }
                log.info("更新用户过期优惠券成功,id={},code={}",
                        list.get(i).getId(), list.get(i).getCouponCode());
            }
        } catch (FanZoneException e) {
            log.error("处理用户超时优惠券失败,{}", e.getMessage());
            e.printStackTrace();
        }
    }

    //处理用户超时未使用的优惠券
    @Override
    public void cancelUserCouponUnuse(String id) {
        userCouponMapper.cancelUserCouponOverTime(id);
    }

    @Override
    public List<TcUserCouponDTO> findUserCouponBybusiness(BussinessDTO bussinessDTO) {
        List<TcUserCouponDTO> list = userCouponMapper.findUserCouponByBusiness(bussinessDTO);
        Date startTime = DaoUtils.setStartTime().getTime();
        Date endTime = DaoUtils.setEndTime().getTime();
        List<TcUserCouponDTO> tempList = new ArrayList<>();
        if (list != null && list.size() > 0) {

            if (list != null && list.size() > 0)
                for (int m = 0; m < list.size(); m++) {
                    if (list.get(m).getUpdateTime().compareTo(startTime) == 1 &&
                            list.get(m).getUpdateTime().compareTo(endTime) == -1) {
                        tempList.add(list.get(m));
                    }
                }
        }
        if (tempList != null && tempList.size() > 0) {
            String bussinessId = tempList.get(0).getBussinessId();
            if (StringUtils.isNotEmpty(bussinessId)) {
                List<TcCouponDTO> tcCoupon = tcCouponService.findCouponByBusiness(bussinessDTO);
                for (int j = 0; j < tcCoupon.size(); j++) {
                    for (int i = 0; i < tempList.size(); i++) {
                        if (StringUtils.equals(tcCoupon.get(j).getCouponId(), tempList.get(i).getCouponId())) {
                            BeanUtils.copyProperties(tcCoupon.get(j), tempList.get(i).getTcCouponDTO());
                        }
                    }
                }

            }
        }
        return tempList;
    }

    @Override
    public TcUserCouponDTO findByCouponCode(String couponCode) {
        return userCouponMapper.findByCouponCode(couponCode);
    }

    @Override
    public void save(TcUserCouponDTO tcUserCoupon) {
        userCouponMapper.updateuserCouponByCode(tcUserCoupon.getCouponCode());
    }


    @Override
    public List<TcUserCouponDTO> findCouponByopenidAndCouponId(TcUserCouponDTO tcUserCouponDTO) {
        return userCouponMapper.findCouponByopenidAndCouponId(tcUserCouponDTO);
    }
}
